import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Picker, ImageUploader, TextArea, Checkbox, Space } from 'antd-mobile';
import { AddOutline, DownOutline, UpOutline, ExclamationCircleOutline } from 'antd-mobile-icons';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav";
import { useSearchParams } from 'react-router-dom';
const { getWorldBookDetails, uploadWorldImage, getUserWorldBookList, createWorldRole, getUserWorldBookDetails } = $globalServicer('world')
const { getUserInfo, getSettings, getUpdateUserInfo } = $globalServicer('My')
import { handleImageUpload } from '@/utils/upload'
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const WorldCreationForm = () => {
  const [form] = Form.useForm();
  const [worldBookList, setWorldBookList] = useState([]);
  const [params] = useSearchParams();
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false);
  const [avatarError, setAvatarError] = useState('');
  const [uploadFailed, setUploadFailed] = useState(false); // 跟踪是否因为文件大小超限导致上传失败
  console.log("🚀 ~ ItemCrad ~ params:", params)
  const id = params.get('id');
  console.log(`------id`, id)
  const customNavigate = $globalNavigate()

  useEffect(() => {
    getUserInfo().then(res => {
      let result = {
        ...res.user,
        cover: [{
          url: res?.user?.cover,
          path: res?.user?.path
        }]
      }
      form.setFieldsValue(result)
    });
  }, [])

  // 验证头像是否已上传
  const isImageUploaded = (imageField) => {
    if (!imageField || !Array.isArray(imageField) || imageField.length === 0) {
      return false;
    }
    const image = imageField[0];
    
    // 检查是否有有效的URL或path
    const hasUrl = !!(image.url || image.path);
    return hasUrl;
  };

  const onFinish = (values) => {
    debugger
    console.log('Form values:', values);
    if (submitting) return; // 如果正在提交，直接返回
    
    // 验证头像是否已上传
    if (!isImageUploaded(values.cover)) {
      // 判断是没有上传图像还是因为图片超出大小导致内容为空
      if (uploadFailed) {
        // 如果是因为上传失败（文件大小超限或其他原因）导致的内容为空
        if (avatarError.includes('图片上传失败，请调整图片大小')) {
          setAvatarError('图片上传失败，请调整图片大小');
          showErrorToast('图片上传失败，请调整图片大小');
        } else {
          setAvatarError('图片上传失败，请重试');
          showErrorToast('图片上传失败，请重试');
        }
      } else {
        // 如果没有上传失败记录，说明是用户没有选择图片
        setAvatarError('请上传头像');
        showErrorToast('请上传头像');
      }
      return;
    }
    
    let submitData = {
      ...values,
      cover: values.cover[0].path || values.cover[0].url,
    }
    try {
      setSubmitting(true);
      getUpdateUserInfo(submitData).then(res => {
        showSuccessToast('修改成功')
        customNavigate(`/my`)
      })
    } catch (error) {
      showErrorToast('修改失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={styles.userInfoPage}>
      <div className={styles.header}>
        <HeaderNav backArrow={true} title="编辑资料" rightContent="保存" onRightClick={() => form.submit()}></HeaderNav>
      </div>
      <div className={styles.mainContent}>
        <Form
          form={form}
          onFinish={onFinish}
        >
          {/* 头像上传区域 */}
          <div className={styles.avatarSection}>
            <div className={styles.avatarContainer}>
              <Form.Item name="cover" noStyle>
                <ImageUploader
                  style={{ '--cell-size': '96px' }}
                  className={styles.avatarUploader}
                  upload={async (file) => {
                    try {
                      setAvatarError(''); // 清除之前的错误
                      setUploadFailed(false); // 清除上传失败状态
                      const result = await handleImageUpload(file);
                      return result;
                    } catch (error) {
                      if (error.message === '图片大小超过2MB限制') {
                        setAvatarError('图片上传失败，请调整图片大小');
                        setUploadFailed(true); // 标记为文件大小超限导致的上传失败
                      } else {
                        setAvatarError('图片上传失败，请重试');
                        setUploadFailed(true); // 标记为其他原因导致的上传失败
                      }
                      throw error;
                    }
                  }}
                  maxCount={1}
                  onDelete={() => {
                    setAvatarError(''); // 删除图片时清除错误
                    setUploadFailed(false); // 删除图片时清除上传失败状态
                    return { beforeDelete: () => true };
                  }}
                />
              </Form.Item>
              <div className={styles.editButton}>
                <span className={styles.editIcon}>edit</span>
              </div>
            </div>
            <label className={styles.uploadLabel} htmlFor="avatarUpload">上传头像(仅支持2MB大小以下图片上传)</label>
            {avatarError && (
              <div className={styles.errorText}>{avatarError}</div>
            )}
          </div>

          {/* 用户名输入区域 */}
          <div className={styles.inputSection}>
            <label className={styles.inputLabel} htmlFor="username">用户名</label>
            <div className={styles.inputWrapper}>
              <Form.Item name="name" noStyle>
                <Input 
                  className={styles.usernameInput}
                  placeholder="用户名"
                  id="username"
                  style={{ color: '#ffffff' }}
                />
              </Form.Item>
              <span className={styles.chevronIcon}>chevron_right</span>
            </div>
          </div>

        </Form>
      </div>
    </div>
  );
};

export default WorldCreationForm;